package wafteam.others;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import wafteam.comicview.R;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;


public class DownloadFromURL extends AsyncTask<String, String, String> {
	
	View parentContext;
	ListView chapList;
	ComicArrayAdapter adapter;
	
	public DownloadFromURL(View cntx){
		this.parentContext = cntx;
	}
	
	@Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
	
	// Downloading images in background
	@Override
	protected String doInBackground(String... f_url) {
		int count;
		try{
			URL url = new URL(f_url[0]);
			URLConnection connection = url.openConnection();
			connection.setRequestProperty("METHOD", "GET");
			connection.setDoOutput(true);
			connection.connect();
			int lenghtOfFile = connection.getContentLength();
			
			// Get the file's name
			int lastSlash = url.toString().lastIndexOf('/');
			String fileName;
			fileName = url.toString().substring(lastSlash + 1);
			
			InputStream input = connection.getInputStream();
			OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Comic/"+fileName);
			byte[] data = new byte[1024];
			long total = 0;
			count = 0;
			while ((count = input.read(data)) > 0){
				total += count;
				publishProgress(String.valueOf((total*100)/lenghtOfFile));
				output.write(data, 0, count);
			}
			
			output.flush();
			
			input.close();
			output.close();
			
		} catch (Exception e){
			Log.e("ERROR: ", e.getMessage());
		}
		
		return null;
	}
	
	// Updating progress bar
	@Override
	protected void onProgressUpdate(String... progress){
		super.onProgressUpdate(progress);
		int values = Integer.parseInt(progress[0]);
		TextView percents = (TextView) this.parentContext.findViewById(R.id.percents);
		percents.setText(values+"%");
	}
	
	@Override 
	protected void onPostExecute(String f_url){
		ViewFlipper switcher = (ViewFlipper) parentContext.findViewById(R.id.download_switch);
		switcher.showPrevious();
	}
}
